<template>
  <div class="user-management">
    <h1>用户信息管理</h1>
    
    <!-- 筛选表单 -->
    <div class="filter-form">
      <el-form :inline="true" :model="filterParams" class="demo-form-inline">
        <el-form-item label="用户昵称">
          <el-input v-model="filterParams.nickname" placeholder="请输入昵称" clearable></el-input>
        </el-form-item>
        
        <el-form-item label="联系电话">
          <el-input v-model="filterParams.phone" placeholder="请输入电话" clearable></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="fetchUsers">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 用户表格 -->
    <el-table :data="userList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="userId" label="用户ID" width="80" align="center"></el-table-column>
      <el-table-column prop="username" label="账号" width="150"></el-table-column>
      <el-table-column prop="nickname" label="昵称" width="120"></el-table-column>
      <el-table-column label="头像" width="100" align="center">
        <template #default="{row}">
          <el-avatar :size="50" :src="row.avatarUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="150"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="role" label="角色" width="120">
        <template #default="{row}">
          <el-tag :type="getRoleTagType(row.role)">
            {{ formatRole(row.role) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{row}">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(row.userId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="filterParams.page"
        v-model:page-size="filterParams.size"
        :page-sizes="[5, 10, 20, 50]"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="fetchUsers"
        @current-change="fetchUsers"
      ></el-pagination>
    </div>
    
    <!-- 编辑用户对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      :title="editDialogTitle" 
      width="600px"
      @closed="resetEditForm"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="editForm.userId" disabled></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="后厨人员" value="kitchen"></el-option>
            <el-option label="普通用户" value="customer"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像URL" prop="avatarUrl">
          <el-input v-model="editForm.avatarUrl" placeholder="请输入头像URL"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 用户列表数据
const userList = ref([])
const totalCount = ref(0)
const loading = ref(false)

// 筛选参数
const filterParams = ref({
  page: 1,
  size: 10,
  nickname: '',
  phone: ''
})

// 编辑对话框相关
const editDialogVisible = ref(false)
const editDialogTitle = ref('编辑用户')
const editForm = ref({
  userId: null,
  username: '',
  nickname: '',
  phone: '',
  email: '',
  role: '',
  avatarUrl: ''
})
const editFormRef = ref(null)

// 表单验证规则
const editRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    loading.value = true
    // 过滤掉空值的参数
    const params = {
      page: filterParams.value.page,
      size: filterParams.value.size,
      ...(filterParams.value.nickname && { nickname: filterParams.value.nickname }),
      ...(filterParams.value.phone && { phone: filterParams.value.phone })
    }
    
    const response = await axios.get('http://localhost:8081/user/list', { params })
    
    if (response.data.code === 200) {
      userList.value = response.data.data.list || response.data.data.records || response.data.data
      totalCount.value = response.data.data.total || response.data.data.length || 0
    } else {
      ElMessage.error(response.data.message || '获取用户列表失败')
    }
  } catch (error) {
    ElMessage.error('请求失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 重置筛选条件
const resetFilter = () => {
  filterParams.value = {
    page: 1,
    size: 10,
    nickname: '',
    phone: ''
  }
  fetchUsers()
}

// 编辑用户
const handleEdit = (row) => {
  editDialogTitle.value = '编辑用户信息'
  editForm.value = {
    userId: row.userId,
    username: row.username,
    nickname: row.nickname,
    phone: row.phone,
    email: row.email,
    role: row.role,
    avatarUrl: row.avatarUrl
  }
  editDialogVisible.value = true
}

// 删除用户
const handleDelete = (userId) => {
  ElMessageBox.confirm('确定要删除这个用户吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`http://localhost:8081/user/delete/${userId}`)
      ElMessage.success('删除成功')
      fetchUsers() // 刷新列表
    } catch (error) {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    
    const response = await axios.post('http://localhost:8081/user/update', editForm.value)
    
    if (response.data.code === 200) {
      ElMessage.success('用户信息更新成功')
      editDialogVisible.value = false
      fetchUsers() // 刷新列表
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    if (error.name !== 'ValidateError') {
      ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 重置编辑表单
const resetEditForm = () => {
  editForm.value = {
    userId: null,
    username: '',
    nickname: '',
    phone: '',
    email: '',
    role: '',
    avatarUrl: ''
  }
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化角色显示
const formatRole = (role) => {
  const roles = {
    admin: '管理员',
    kitchen: '后厨人员',
    customer: '普通用户'
  }
  return roles[role] || role
}

// 获取角色标签类型
const getRoleTagType = (role) => {
  const types = {
    admin: 'danger',
    kitchen: 'warning',
    customer: 'success'
  }
  return types[role] || ''
}

// 组件挂载时获取数据
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.el-tag {
  margin: 2px;
}

.el-avatar {
  cursor: pointer;
}
</style>